package cc.cary.warehouse.advice;

import cc.cary.warehouse.common.ErrorConstants;
import cc.cary.warehouse.common.R;
import cc.cary.warehouse.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常绑定
 *
 * @author Cary
 * @date 2023/4/18
 */
@RestControllerAdvice
@Slf4j
public class HttpGlobalExceptionAdvice {
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public R<String> handleBindException(BindException ex) {
        log.error("参数校验异常", ex);
        FieldError fieldError = ex.getFieldError();
        String msg = "";
        if (fieldError != null) {
            msg = fieldError.getDefaultMessage();
        }
        return R.failed(msg);
    }

    /**
     * 一般的参数绑定时候抛出的异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public R<String> handleBindException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        // getFieldError获取的是第一个不合法的参数(P.S.如果有多个参数不合法的话)
        FieldError fieldError = bindingResult.getFieldError();
        String msg = "";
        if (fieldError != null) {
            msg = fieldError.getDefaultMessage();
        }
        log.error("参数校验异常: = {}", e.getMessage());
        return R.failed(msg);
    }

    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public R<String> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return R.failed(e.getMessage());
    }

    /**
     * 拦截所有运行时的全局异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public R<String> runtimeException(RuntimeException e) {
        log.error(e.getMessage(), e);
        return R.failed(ErrorConstants.ERR_UNKNOWN);
    }

    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public R<String> serviceException(ServiceException e) {
        log.error(e.getMessage(), e);
        return R.failed(ErrorConstants.BUSINESS_ERROR);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R<String> exception(Exception e) {
        log.error(e.getMessage(), e);
        return R.failed(ErrorConstants.ERR_UNKNOWN);
    }
}


